<?php

/*
 * Edit by shengxin
 * Click nbfs://nbhost/SystemFileSystem/Templates/Scripting/PHPClass.php to edit this template
 */
namespace app\admin\controller;

use api\mall\model\StoreAttrMapModel;
use api\mall\model\StoreAttrModel;
use api\mall\model\StoreAttrValueModel;
use api\mall\model\StoreBoothModel;
use api\mall\model\StoreTagMapModel;
use api\mall\model\StoreLogModel;
use cmf\controller\AdminBaseController;
use api\mall\model\StoreModel;
use api\mall\model\BoothModel;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Cell\DataType;
use PhpOffice\PhpSpreadsheet\IOFactory;
/**
 * Description of StoreController
 * 
 *
 * @author PC
 */
class StoreController extends AdminBaseController{
    
    public function digital(){
        return $this->_booth(1);
    }
    public function beauty(){
        return $this->_booth(2);
    }
    public function retail(){
        return $this->_booth(3);
    }
    
    public function booth(){
        $bid = $this->request->route('bid',1);
        return $this->_booth($bid);
    }
    
    private function _booth($btype=0){
        $search = $this->request->get('search');
        $model = new StoreBoothModel();
        if(!empty($search)){
           $model = $model->where('booth_name|button_name','like',"%$search%"); 
        }
        $page = $model->where('booth_type',$btype)->paginate(20);
        $itemModel = new StoreModel();
        $nums = $itemModel->field('store_type,count(1) as count')->group('store_type')->select();
        $items = $page->items();
        $arr = [];
        foreach ($items as $item){
            $item['num'] = 0;
            $type = $item['id'];
            foreach ($nums as $num){
                if($num['store_type']==$type){
                    $item['num'] = $num['count'];
                }
            }
            $arr[] = $item;
        }
        $this->assign('booth_type',$btype);
        $this->assign('items',$arr);
        $this->assign('page',$page->render());
        return $this->fetch('booth');
    }
    
    public function add_booth(){
        $type = $this->request->route('type',1);
        $check_count = $type==1?0:1;
        $this->assign('booth_type',$type);
        $this->assign('check_count',$check_count);
        return $this->fetch();
    }
    
    public function edit_booth(){
        $model = new BoothModel();
        $id = $this->request->route('id');
        $booth = $model->where('id',$id)->find();
        if(empty($booth)){
            $this->error('展位不存在');
        }
        $data = $booth->toArray();
        if(!empty($data['item_id'])){
            $itemModel = new StoreModel();
            $item = $itemModel->where('id',$data['item_id'])->find();
            $this->assign('item',$item->toArray());
        }
        $this->assign($data);
        return $this->fetch();
    }
    
    public function subIndex($type=1){
        $type = $this->request->route('type/d',$type);
        $this->assign('type',$type);
        $storeModel = new StoreModel();
        $tags = $storeModel->where('store_type',$type)->field('item_type')->distinct(true)->select();
        
        $search = $this->request->get('search');
        if(!empty($search)){
            $storeModel = $storeModel->where('id|item_name','like','%'.$search.'%');
        }
        $item_type = $this->request->get('key');
        if(!empty($item_type) && $item_type!=='all'){
            $storeModel = $storeModel->where('item_type',$item_type);
        }
        $options = '';
        foreach ($tags as $valobj){
            $val = $valobj['item_type'];
            if($item_type==$val){
            $options .= '<option selected value="'.$val.'">'.$val.'</option>';

            }else{
                $options .= '<option value="'.$val.'">'.$val.'</option>';
            }
        }
        $this->assign('options',$options);
        $status = $this->request->get('item_status/d',4);
        if($status!=4){
            $storeModel = $storeModel->where('item_status',$status);
        }
        
        $page = $storeModel->where('store_type',$type)->order('item_status asc')->order('item_order desc')->paginate(20);
        $boothModel = new BoothModel();
        $booth = $boothModel->where('id',$type)->find();
        $this->assign('booth',$booth->toArray());
        $this->assign('items',$page->items());
        $this->assign('page',$page->render());
        return $this->fetch('index');
    }

    
    public function add(){
        $type = $this->request->route('type/d',1);
        $this->assign('type',$type);
        $storeModel = new StoreModel();
        $items = $storeModel->types();
//        $tagModel = new StoreTagMapModel();
//        $tags = $tagModel->alias('tm')->join('store_item_tag tag','tm.tag_id=tag.id')
//                ->where('tm.item_id',$id)
//                ->field('tag.*')->select();
//            $this->assign('tags',$tags);
        $this->assign('item_types',$items);
        $booth = new StoreBoothModel();
        $bitem = $booth->where('id',$type)->find();
        if($bitem){
            $this->assign('booth_type',$bitem->booth_type);
        }
        $item_images = [];
        for($i=0;$i<6;$i++){
                $item_images[] = ['type'=>'image2','value'=>''];
            }
        $item_id = '000000';
        $model = new StoreTagMapModel();
        $model->where('item_id',$item_id)->delete();
        $this->assign('item_images',$item_images);
        return $this->fetch();
    }
    
    public function edit(){

        $id = $this->request->route('id');
        $storeModel = new StoreModel();
        $data = $storeModel->where('id',$id)->find();
        if($data){
            $item_images = [];
            $count = 0;
            if($data->item_images){
                $images = json_decode($data->item_images);
                 foreach($images as $vo){
                     $img = cmf_get_image_preview_url($vo);
                     $item_images[] = ['type'=>'image2','value'=>$img];
                     $count++;
                 }
            }
            for($i=$count;$i<6;$i++){
                $item_images[] = ['type'=>'image2','value'=>''];
            }
            $data->item_images = $item_images;
            $this->assign($data->toArray());
            $tagModel = new StoreTagMapModel();
            $tags = $tagModel->alias('tm')->join('store_item_tag tag','tm.tag_id=tag.id')
                ->where('tm.item_id',$id)
                ->field('tag.*')->select();
            $this->assign('tags',$tags);

            $attrModel = new StoreAttrModel();
            $attrs = $attrModel->where('item_id',$id)->select();
            $this->assign('attrs',$attrs);
        }

        $items = $storeModel->types();
        $this->assign('item_types',$items);
        return $this->fetch();
    }
    public function orderList2(){
        return $this->orderList(1);
    }
    public function orderList($type=0){
        $order_id = $this->request->get('order_id');
        $user_info = $this->request->get('user_login');
        $type = $this->request->route('type/d',$type);
        $date_start = $this->request->get('date_start');
        $date_end_t = $date_start_t = 0;
        if($date_start){
            $date_start_t = strtotime($date_start.' 00:00:00');
        }
        $date_end = $this->request->get('date_end');
        if($date_end){
            $date_end_t = strtotime($date_end.' 23:59:59');
        }
        $status = $this->request->get('status/d');
        
        $this->assign('type',$type);
        $storeModel = new StoreModel();
        //数字藏品
        if($type==1){
            $storeModel = $storeModel->where('store_item.booth_type',1);
        }else{
            $storeModel = $storeModel->where('store_item.booth_type','<>',1);
        }
        if($order_id){
            $storeModel = $storeModel->whereLike('log.id|log.item_name',"%$order_id%");
        }
        if($user_info){
             $storeModel = $storeModel->whereLike('user.user_id|user.user_nickname|user.mobile',"%$user_info%");
        }
        if($status>-1){
            $storeModel = $storeModel->where('log.status',$status);
        }
        
        if($date_end_t>$date_start_t){
            $storeModel = $storeModel->whereBetween('log.create_time',[$date_start_t,$date_end_t]);
        }
        //导出
        if($this->request->get('export')){
            $list = $storeModel
            ->field('log.*,user.id uid,user.user_nickname,user.mobile,user.user_id,user.avatar')
            ->alias('store_item')
            ->join('store_log log','log.item_id=store_item.id')
            ->join('user','log.user_id=user.id')
            ->order('log.create_time desc')->limit(0,1000)->select();
            return $this->export($list);
        }else{
            $page = $storeModel
            ->field('log.*,store_item.item_icon,user.id uid,user.user_nickname,user.mobile,user.user_id,user.avatar')
            ->alias('store_item')
            ->join('store_log log','log.item_id=store_item.id')
            ->join('user','log.user_id=user.id')
            ->order('log.create_time desc')->paginate();
            $page->appends([
                'date_start'=>$date_start,
                'date_end'=>$date_end,
                'user_login'=>$user_info,
                'status'=>$status
            ]);
            $this->assign('items',$page->items());
            $this->assign('page',$page->render());
            if($type==1){
                 return $this->fetch('order_dz');
            }
            return $this->fetch('order_list');
        }
        
    }

    public function beautyOrder(){
        return $this->orderList(2);
    }

    public function retailOrder(){
        return $this->orderList(3);
    }

    public function attr(){
        $id = $this->request->route('id');
        $this->assign('id',$id);
        $storeModel = new StoreModel();
        $data = $storeModel->where('id',$id)->find();
        if(empty($data)) {
            return $this->error('找不到该商品');
        }
        $this->assign($data->toArray());
        $attr_model = new StoreAttrModel();
        $attr_name = $attr_model->where('item_id',$id)->select();
        $main_id = [];
        foreach ($attr_name as $item){
            if($item['main']){
                $main_id[] = $item['id'];
                break;
            }
        }
        $attr_value = new StoreAttrValueModel();
        $attr_value_list = $attr_value->where('item_id',$id)->order('order_id asc')->select();
        //属性值列表
//        $vlist = [];
//        foreach ($attr_name as $item){
//            $attr_id = $item['id'];
//            $main = $item['main'];
//            foreach ($attr_value_list as $value){
//                if($value['attr_id'] == $attr_id){
//                    $vlist[] = $value['id'];
//                }
//            }
//        }
        $vmapModel = new StoreAttrMapModel();
        
        $arr = [];
        foreach ($attr_name as $item){
            $item_id = $item['id'];
            $main = $item['main'];
            $tmp = [
                'attr_id'=>$item_id,
                'name'=>$item['attr_name'],
                'main'=>$main,
                'value'=>[]
            ];
            foreach ($attr_value_list as $value){
                if($value['attr_id'] == $item_id){
                    $vitem = [
                        'id'=>$value['id'],
                        'value'=>$value['attr_value'],
//                        'price'=>0,
//                        'count'=>0,
                        'order_id'=>$value['order_id']
                    ];
//                    foreach ($attr_map as $vmapitem){
//                        if($vmapitem['attr_value_id']==$value['id']){
//                            $vitem['price'] = $vmapitem['price'];
//                            $vitem['count'] = $vmapitem['count'];
//                        }
//                    }
                    $tmp['value'][] = $vitem;
                }
            }
            $arr[] = $tmp;
        }
        $attr_map = $vmapModel->where('item_id',$id)->select();
        foreach ($attr_map as &$map){
            $name = '';
            $attrs = explode(',',$map['attr_value_id']);
            foreach($attrs as $attr){
                foreach ($attr_value_list as $item){
                    if($attr == $item['id']){
                        $name = $name.$item['attr_value'].',';
                    }
                }
            }
            $name = substr($name, 0, -1);
            $map['name'] = $name;
        }
        $this->assign('attr_map',$attr_map);
        $this->assign('attr_item',$arr);
        return $this->fetch();
    }

    public function dela(){
        $id = $this->request->route('id');
        $model = new StoreAttrModel();
        $model->where('id',$id)->delete();
        $model = new StoreAttrValueModel();
        $model->where('attr_id',$id)->delete();
        $this->success('删除成功');
    }
    public function delv(){
        $id = $this->request->route('id');
        $model = new StoreAttrValueModel();
        $model->where('id',$id)->delete();
        $this->success('删除成功');
    }

    /**
     * 设置商品属性排序
     */
    public function order(){
        $dir = $this->request->route('dir/d');
        $aid = $this->request->route('aid');
        $vid = $this->request->route('vid');
        $model = new StoreAttrValueModel();
        if($dir>0){
            $model->where('id',$vid)->setInc('order_id',1);
        }else{
            $model->where('id',$vid)->setDec('order_id',1);
        }
        $this->success('修改成功');
    }
    
    /**
     * 设置商品排序
     */
    public function set_order(){
        $id = $this->request->post('id');
        $order = $this->request->post('order/d',1000);
        $model = new StoreModel();
        $model->where('id',$id)->update([
            'item_order'=>$order
        ]);
        $this->success('设置成功');
    }
    
    public function order_detail(){
        $orderid = $this->request->get('orderid');
        $storeModel = new StoreModel();
        $order = $storeModel->where('log.id',$orderid)
            ->field('log.*,store_item.item_icon,store_item.item_price,user.id uid,user.user_nickname,user.mobile,user.user_id,user.avatar')
            ->alias('store_item')
            ->join('store_log log','log.item_id=store_item.id')
            ->join('user','log.user_id=user.id')
            ->order('log.create_time desc')->find();
                
        if($order && $order['group_id']){
            $model = new StoreLogModel();
            $gid = $order['group_id'];
            $orders = $model->where('group_id',$gid)->select();
            $this->assign('list',$orders);
        }else{
            $this->assign('list',[$order]);
        }
        $addr_id = $order['address_id'];
        if($addr_id){
            $addrmodel = new \api\mall\model\AddressModel();
            $addr = $addrmodel->where('id',$addr_id)->find();
            $this->assign('addr',$addr);
        }
        $this->assign('order',$order);
        return $this->fetch();
    }


    
    public function delete_bmodel(){
        $model = new BoothModel();
        $id = $this->request->route('id');
        $booth = $model->where('id',$id)->find();
        if(empty($booth)){
            $this->error('展位不存在');
        }
        $model->where('id',$id)->update([
            'model_url'=>null
        ]);
        return $this->success('删除成功');
    }
    
        
    public function delete_model(){
        $model = new StoreModel();
        $id = $this->request->route('id');
        $item = $model->where('id',$id)->find();
        if(empty($item)){
            $this->error('商品不存在');
        }
        $model->where('id',$id)->update([
            'model_url'=>null
        ]);
        return $this->success('删除成功');
    }

    public function delete_img() {
        $model = new StoreModel();
        $id = $this->request->route('id');
        $item = $model->where('id',$id)->find();
        if(empty($item)){
            $this->error('商品不存在');
        }
        $img = $this->request->get('path');
        $images = json_decode($item->item_images,true);
        $nimgs = [];
        foreach ($images as $val){
            if($val!=$img){
                $nimgs[] = $val;
            }
        }
        $model->where('id',$id)->update([
            'item_images'=> json_encode($nimgs)
        ]);
        return $this->success('删除成功');
    }
    
    public function edit_logistics(){
        $order_id = $this->request->get('order_id');
        $model = new \api\mall\model\StoreLogModel();
        $order = $model->where('id',$order_id)->find();
        if(empty($order)){
            $this->error('订单不存在');
        }
        $this->assign($order->toArray());
        return $this->fetch();
    }
    
    public function property(){
        $id = $this->request->route('id');
        $this->assign('id',$id);
        $storeModel = new StoreModel();
        $data = $storeModel->where('id',$id)->find();
        if(empty($data)) {
            return $this->error('找不到该商品');
        }
        $this->assign($data->toArray());

        $model = new \api\mall\model\PropertyModel();
        $arr = $model->where('item_id',$id)->order('item_order asc')->select();
        if(count($arr)>0){
            $arr[0]['no_up'] = 1;
            $arr[count($arr)-1]['no_down'] = 1;

        }
        $this->assign('attr_item',$arr);
        return $this->fetch('property');
    }
    
    public function export($list){
        $data = [];
        $line=1;//x=		用户	收货地址
        $data['A1'] = '订单编号';
        $data['B1'] = '商品编号';
        $data['C1'] = '商品名称';
        $data['D1'] = '价格';
        $data['E1'] = '数量';
        $data['F1'] = '总价';
        $data['G1'] = '用户ID';
        $data['H1'] = '用户昵称';
        $data['I1'] = '手机号';
        $data['J1'] = '收货地址';
        $data['K1'] = '物流编号';
        $data['L1'] = '下单时间';
        $data['M1'] = '付款时间';
        $data['N1'] = '订单状态';
        foreach ($list as $v){
            $line++;
            $data['A'.$line] = $v['id'];
            $data['B'.$line] = $v['item_id'];
            $data['C'.$line] = $v['item_name'];
            $data['D'.$line] = $v['item_price'];
            $data['E'.$line] = $v['item_num'];
            $data['F'.$line] = $v['cost'];
            $data['G'.$line] = $v['user_id'];
            $data['H'.$line] = $v['user_nickname'];
            $data['I'.$line] = $v['mobile'];
            $data['J'.$line] = $v['address'];
            $data['K'.$line] = $v['logistics'];
            $data['L'.$line] = date('Y-m-d H:i:s',intval($v['create_time']));
            $data['M'.$line] = $v['pay_time'];
            $data['N'.$line] = $v['desc'];
        }
        $rs = $this->exportExcel($data,'daochu',['savePath'=>'upload/1.xlsx']);
        return $this->redirect('/upload/1.xlsx');
    }
    
    /**
    * Excel导出，TODO 可继续优化
    *
    * @param array  $datas      导出数据，格式['A1' => 'XXXX公司报表', 'B1' => '序号']
    * @param string $fileName   导出文件名称
    * @param array  $options    操作选项，例如：
    *                           bool   print       设置打印格式
    *                           string freezePane  锁定行数，例如表头为第一行，则锁定表头输入A2
    *                           array  setARGB     设置背景色，例如['A1', 'C1']
    *                           array  setWidth    设置宽度，例如['A' => 30, 'C' => 20]
    *                           bool   setBorder   设置单元格边框
    *                           array  mergeCells  设置合并单元格，例如['A1:J1' => 'A1:J1']
    *                           array  formula     设置公式，例如['F2' => '=IF(D2>0,E42/D2,0)']
    *                           array  format      设置格式，整列设置，例如['A' => 'General']
    *                           array  alignCenter 设置居中样式，例如['A1', 'A2']
    *                           array  bold        设置加粗样式，例如['A1', 'A2']
    *                           string savePath    保存路径，设置后则文件保存到服务器，不通过浏览器下载
    */
   function exportExcel(array $datas, string $fileName = '', array $options = []): bool
   {
           if (empty($datas)) {
               return false;
           }
        try{
           set_time_limit(0);
           /** @var Spreadsheet $objSpreadsheet */
           $objSpreadsheet = app(Spreadsheet::class);
           /* 设置默认文字居左，上下居中 */
           $styleArray = [
               'alignment' => [
                   'horizontal' => Alignment::HORIZONTAL_LEFT,
                   'vertical'   => Alignment::VERTICAL_CENTER,
               ],
           ];
           $objSpreadsheet->getDefaultStyle()->applyFromArray($styleArray);
           /* 设置Excel Sheet */
           $activeSheet = $objSpreadsheet->setActiveSheetIndex(0);

           /* 打印设置 */
           if (isset($options['print']) && $options['print']) {
               /* 设置打印为A4效果 */
               $activeSheet->getPageSetup()->setPaperSize(PageSetup:: PAPERSIZE_A4);
               /* 设置打印时边距 */
               $pValue = 1 / 2.54;
               $activeSheet->getPageMargins()->setTop($pValue / 2);
               $activeSheet->getPageMargins()->setBottom($pValue * 2);
               $activeSheet->getPageMargins()->setLeft($pValue / 2);
               $activeSheet->getPageMargins()->setRight($pValue / 2);
           }

           /* 行数据处理 */
           foreach ($datas as $sKey => $sItem) {
               /* 默认文本格式 */
               $pDataType = DataType::TYPE_STRING;

               /* 设置单元格格式 */
               if (isset($options['format']) && !empty($options['format'])) {
                   $colRow = Coordinate::coordinateFromString($sKey);

                   /* 存在该列格式并且有特殊格式 */
                   if (isset($options['format'][$colRow[0]]) &&
                       NumberFormat::FORMAT_GENERAL != $options['format'][$colRow[0]]) {
                       $activeSheet->getStyle($sKey)->getNumberFormat()
                           ->setFormatCode($options['format'][$colRow[0]]);

                       if (false !== strpos($options['format'][$colRow[0]], '0.00') &&
                           is_numeric(str_replace(['￥', ','], '', $sItem))) {
                           /* 数字格式转换为数字单元格 */
                           $pDataType = DataType::TYPE_NUMERIC;
                           $sItem     = str_replace(['￥', ','], '', $sItem);
                       }
                   } elseif (is_int($sItem)) {
                       $pDataType = DataType::TYPE_NUMERIC;
                   }
               }

               $activeSheet->setCellValueExplicit($sKey, $sItem, $pDataType);

               /* 存在:形式的合并行列，列入A1:B2，则对应合并 */
               if (false !== strstr($sKey, ":")) {
                   $options['mergeCells'][$sKey] = $sKey;
               }
           }

           unset($datas);

           /* 设置锁定行 */
           if (isset($options['freezePane']) && !empty($options['freezePane'])) {
               $activeSheet->freezePane($options['freezePane']);
               unset($options['freezePane']);
           }

           /* 设置宽度 */
           if (isset($options['setWidth']) && !empty($options['setWidth'])) {
               foreach ($options['setWidth'] as $swKey => $swItem) {
                   $activeSheet->getColumnDimension($swKey)->setWidth($swItem);
               }

               unset($options['setWidth']);
           }

           /* 设置背景色 */
           if (isset($options['setARGB']) && !empty($options['setARGB'])) {
               foreach ($options['setARGB'] as $sItem) {
                   $activeSheet->getStyle($sItem)
                       ->getFill()->setFillType(Fill::FILL_SOLID)
                       ->getStartColor()->setARGB(Color::COLOR_YELLOW);
               }

               unset($options['setARGB']);
           }

           /* 设置公式 */
           if (isset($options['formula']) && !empty($options['formula'])) {
               foreach ($options['formula'] as $fKey => $fItem) {
                   $activeSheet->setCellValue($fKey, $fItem);
               }

               unset($options['formula']);
           }

           /* 合并行列处理 */
           if (isset($options['mergeCells']) && !empty($options['mergeCells'])) {
               $activeSheet->setMergeCells($options['mergeCells']);
               unset($options['mergeCells']);
           }

           /* 设置居中 */
           if (isset($options['alignCenter']) && !empty($options['alignCenter'])) {
               $styleArray = [
                   'alignment' => [
                       'horizontal' => Alignment::HORIZONTAL_CENTER,
                       'vertical'   => Alignment::VERTICAL_CENTER,
                   ],
               ];

               foreach ($options['alignCenter'] as $acItem) {
                   $activeSheet->getStyle($acItem)->applyFromArray($styleArray);
               }

               unset($options['alignCenter']);
           }

           /* 设置加粗 */
           if (isset($options['bold']) && !empty($options['bold'])) {
               foreach ($options['bold'] as $bItem) {
                   $activeSheet->getStyle($bItem)->getFont()->setBold(true);
               }

               unset($options['bold']);
           }

           /* 设置单元格边框，整个表格设置即可，必须在数据填充后才可以获取到最大行列 */
           if (isset($options['setBorder']) && $options['setBorder']) {
               $border    = [
                   'borders' => [
                       'allBorders' => [
                           'borderStyle' => Border::BORDER_THIN, // 设置border样式
                           'color'       => ['argb' => 'FF000000'], // 设置border颜色
                       ],
                   ],
               ];
               $setBorder = 'A1:' . $activeSheet->getHighestColumn() . $activeSheet->getHighestRow();
               $activeSheet->getStyle($setBorder)->applyFromArray($border);
               unset($options['setBorder']);
           }

           $fileName = !empty($fileName) ? $fileName : (date('YmdHis') . '.xlsx');

           if (!isset($options['savePath'])) {
               /* 直接导出Excel，无需保存到本地，输出07Excel文件 */
               header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
               header(
                   "Content-Disposition:attachment;filename=" . iconv(
                       "utf-8", "GB2312//TRANSLIT", $fileName
                   )
               );
               header('Cache-Control: max-age=0');//禁止缓存
               $savePath = 'php://output';
           } else {
               $savePath = $options['savePath'];
           }

           ob_clean();
           ob_start();
           $objWriter = IOFactory::createWriter($objSpreadsheet, 'Xlsx');
           $objWriter->save($savePath);
           /* 释放内存 */
           $objSpreadsheet->disconnectWorksheets();
           unset($objSpreadsheet);
           ob_end_flush();
           return true;
       } catch (Exception $e) {
           echo 'error';
           echo $e->message;
           return false;
       }
   }
}
